#include "NoisePlayer.hpp"

static const int SAMPLE_RATE = 44100;

NoisePlayer::NoisePlayer()
{
  m_module = GetModuleHandle(NULL);
  m_playing = false;
  m_amplitude = 0;

  m_waveGenerator = new WaveGenerator();
}

void NoisePlayer::SetAmplitude(short amplitude)
{
  m_amplitude = amplitude;
}

bool NoisePlayer::StartPlaying()
{
  if (m_playing)
    return false;

  GenerateSamples();

  m_waveGenerator->GenerateData(SAMPLE_RATE);
  if (!sndPlaySoundA(m_waveGenerator->GetData(), SND_MEMORY | SND_ASYNC | SND_LOOP))
    return false;

  m_playing = true;
  return true;
}

bool NoisePlayer::StopPlaying()
{
  if (!m_playing)
    return false;

  if (!PlaySound(NULL, NULL, 0))
    return false;

  m_playing = false;
  return true;
}

void NoisePlayer::GenerateSamples()
{
  m_waveGenerator->Clear();

  srand(static_cast<unsigned int>(time(0)));
  for (int i = 0; i < SAMPLE_RATE; i++)
    m_waveGenerator->AddSample((rand() % m_amplitude) * (rand() % 2 == 0 ? -1 : 1));
}